package com.yff.tuan.interceptor;

import java.io.IOException;
import java.util.Date;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import com.yff.tuan.util.ApiConstants;
import com.yff.tuan.util.DateUtil;


/**
 *         1 Add the request id in the response. 
 *         2 Add logId in the context with  logback
 */
public class CustomFilter extends OncePerRequestFilter {
	
	@Override
	protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {
		String rqId = DateUtil.getFormatDate(new Date(), "yyyyMMddHHmmssSSS")+Long.toString((long) (Math.random() * 10000000000L));
		request.setAttribute(ApiConstants.RQID, rqId);
		response.setHeader(ApiConstants.HEADER_RQID, rqId);
		request.getSession().setAttribute("uri", request.getServletPath());
		MDC.put(ApiConstants.RQID, rqId);
		try{
			filterChain.doFilter(request, response);
		}finally{
			MDC.remove(ApiConstants.RQID);
		}
	}
}
